//
//  CommunityLinkServer.m
//  WeCommunity
//
//  Created by mac on 2017/8/9.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "CommunityLinkServer.h"
#import "CommunityLinkModel.h"
#import "PhotoAlbumModel.h"

//leanCloud表名
#define COMMUNITYLINK_CLASS_NAME @"CommunityLink"

static CommunityLinkServer * communityLinkServer = nil;

@implementation CommunityLinkServer

+(CommunityLinkServer *)shared
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        communityLinkServer = [[CommunityLinkServer alloc] init];
        
    });
    return communityLinkServer;
}

#pragma mark - 发布社区数据
-(void)postCommunityWithModel:(PostDynamicModel *)model
                   complete:(void(^)(BOOL success, NSString *error))complete
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        AVObject * dynamic = [AVObject objectWithClassName:COMMUNITYLINK_CLASS_NAME];
        [dynamic setObject:model.content forKey:@"content"];
        [dynamic setObject:@(model.dataType) forKey:@"dataType"];
        [dynamic setObject:model.addLinkUrl forKey:@"linkUrl"];
        //图片资源
        PhotoAlbumModel * albumModel = model.imagelist.firstObject;
        if (!albumModel.fullScreenImage) {
            UIImage *image = [UIImage imageWithCGImage:[[albumModel.asset defaultRepresentation] fullScreenImage]];
            albumModel.fullScreenImage = image;
        }
        NSData *data = UIImageJPEGRepresentation(albumModel.fullScreenImage, 0.5);
        AVFile *file = [AVFile fileWithData:data];
        [dynamic setObject:file forKey:@"imageUrl"];
        
        //用户
        AVUser *currentUser = [AVUser currentUser];
        [dynamic setObject:currentUser forKey:@"contact"];
        
        [dynamic saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (succeeded) {
                    complete(YES,nil);
                }else{
                    complete(NO,error.userInfo[@"NSLocalizedDescription"]);
                }
            });
        }];
    });
}

#pragma mark - 获取社区数据
-(void)loadCommunityLinkDataWithType:(NSInteger)type
                            loadDate:(NSDate *)loadDate
                           loadCount:(NSInteger)loadCount
                            complete:(void(^)(BOOL success, NSString *error, NSArray *dataArray))complete
{
    AVQuery *query = [AVQuery queryWithClassName:COMMUNITYLINK_CLASS_NAME];
    
    //根据条件查询不同的数据
    if (!loadDate) {
        loadDate = [NSDate date];
    }
    [query whereKey:@"dataType" equalTo:@(type)];
    [query whereKey:@"createdAt" lessThan:loadDate];//查询日期之前创建的数据
    [query orderByDescending:@"createdAt"]; //按时间排序 降序
    
    
    query.limit = loadCount; // 最多返回 x 条结果
    // owner 为 Pointer，指向 _User 表
    [query includeKey:@"contact"];
    // image 为 File
    [query includeKey:@"imageUrl"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }else{
            NSMutableArray * dataList = [NSMutableArray array];
            for (NSDictionary * dic in objects) {
                CommunityLinkModel * model = [CommunityLinkModel setValueFormObject:dic];
                [dataList addObject:model];
            }
            //加入广告
            dataList = [[GooGleAdMobMgr shared] getAdMobModelDataWithArray:dataList];
            
            complete(YES,nil,dataList);
        }
    }];
}

#pragma mark - 点赞
-(void)likeOrUnLikeDataWithCommunity:(CommunityLinkModel *)model
                            complete:(void(^)(BOOL success, NSString *error, id resultModel))complete
{
    
    //查询最新的数据
    [self findCommunityDataWithObjectId:model.objectId complete:^(BOOL success, NSString *error, DynamicModel *resultModel) {
        if (success) {
            model.likeList = [resultModel.likeList mutableCopy];
            
            AVObject * dynamic = [AVObject objectWithClassName:COMMUNITYLINK_CLASS_NAME objectId:model.objectId];
            if (!model.isLike) {
                [dynamic addObject:[UserInfoManger shared].contact.objectId forKey:@"likeList"];
            }else{
                [dynamic removeObject:[UserInfoManger shared].contact.objectId forKey:@"likeList"];
            }
            [dynamic saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                if (succeeded) {
                    
                    if (!model.isLike) {
                        [model.likeList addObject:[UserInfoManger shared].contact.objectId];
                    }else{
                        [model.likeList removeObject:[UserInfoManger shared].contact.objectId];
                    }
                    complete(YES,nil,model);
                }else{
                    complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
                }
            }];
            
        }else{
            complete(NO,error,nil);
        }
    }];
}

#pragma mark - 查询某一动态数据
-(void)findCommunityDataWithObjectId:(NSString *)objectId
                            complete:(void(^)(BOOL success,NSString *error, id resultModel))complete
{
    AVQuery *query = [AVQuery queryWithClassName:COMMUNITYLINK_CLASS_NAME];
    // owner 为 Pointer，指向 _User 表
    [query includeKey:@"contact"];
    // image 为 File
    [query includeKey:@"imageUrl"];
    [query getObjectInBackgroundWithId:objectId block:^(AVObject *object, NSError *error) {
        if (!error) {
            CommunityLinkModel * model = [CommunityLinkModel setValueFormObject:object];
            complete(YES,nil,model);
        }else{
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }
    }];
}

@end
